package timbap.visualizer.impl.context.textures;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import processing.core.PApplet;
import processing.core.PImage;
import timbap.visualizer.api.context.Configuration;
import timbap.visualizer.api.context.textures.LRUCache;
import timbap.visualizer.api.context.playlist.PlaylistManager;
import timbap.visualizer.api.model.PlaylistEntry;

import java.awt.*;

public class CircleTextureCacheManagerImpl extends AbstractP5TextureCacheManager {

    private static final Log LOG = LogFactory.getLog(CircleTextureCacheManagerImpl.class);

    private static final String BLURRED_CIRCLE_FILENAME = "circle_blurred.bmp";
    private static final int MASK_CACHE_SIZE = 20;

    private PImage sourceMask;
    private LRUCache<Dimension, int[]> maskCache = new LRUCache<Dimension,int[]>(MASK_CACHE_SIZE);

    public CircleTextureCacheManagerImpl(PApplet pP5Applet, Configuration pCfg, PlaylistManager pPlaylistManager) {
        super(pP5Applet, pCfg, pPlaylistManager);
        sourceMask = getP5Applet().loadImage(BLURRED_CIRCLE_FILENAME);
    }
    
    private int[] generateCircleMask(int xResolution, int yResolution) {
        int[] tGeneratedCircleMask = new int[xResolution * yResolution];
        for (int iY=0; iY < yResolution; iY++) {
            for (int iX=0; iX < xResolution; iX++) {
                int currentIndex = iY * (xResolution) + iX;
                int iXMapped = (int) PApplet.map(iX, 0, xResolution, 0, sourceMask.width);
                int iYMapped = (int) PApplet.map(iY, 0, yResolution, 0, sourceMask.height);
                int value = sourceMask.get(iXMapped, iYMapped);
                tGeneratedCircleMask[currentIndex] = value;
            }
        }
        maskCache.put(new Dimension(xResolution, yResolution),tGeneratedCircleMask);
        return tGeneratedCircleMask;
    }

	@Override
	public PImage loadArtworkTexture(PlaylistEntry pPlaylistEntry) {
	    LOG.debug("Trying to load texture for '" + pPlaylistEntry.getAudioFile() + "' ... ");
		PImage tArtworkTexture = super.loadArtworkTexture(pPlaylistEntry);
		if (tArtworkTexture != null) {
            LOG.debug("Loaded texture dimensions are " + tArtworkTexture.width + "x" + tArtworkTexture.height);
            int[] tMask = maskCache.get(new Dimension(tArtworkTexture.width, tArtworkTexture.height));
            if (tMask == null) {
                tMask = generateCircleMask(tArtworkTexture.width, tArtworkTexture.height);
            }
            if (tMask != null) {
                tArtworkTexture.mask(tMask);
		    }
            LOG.debug("Successful.");
        } else {
            LOG.warn("Failed loading texture for '" + pPlaylistEntry.getAudioFile() + "'. ");
        }
		return tArtworkTexture;
	}
    
}
